//
//  WBHomeViewController.swift
//  SinaWeiBo
//
//  Created by Frank on 2017/7/10.
//  Copyright © 2017年 Frank. All rights reserved.
//

import UIKit

//定义全局常量，尽量使用private
/// 原创微博可重用 cell id
private let originalCellId = "originalCellId"
/// 被转发微博的可重用 cell id
private let retweetedCellId = "retweetedCellId"

class WBHomeViewController: WBBaseViewController {
    
    // 列表视图模型
    lazy var listViewModel = WBStatusListViewModel()
    //加载数据
    override func loadData() {
             print("准备刷新")
            // Xcode 8.0 的刷新控件，beginRefreshing 方法，什么都不显示！
            //结束刷新控件
            self.refreshControl?.beginRefreshing()
            // 模拟演示加载数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2, execute: {
                self.listViewModel.loadStatus(pullup: self.isPullup, completion: { (isSuccess, shouldRefresh) in
                    print("加载数据结束")
                    // 结束刷新控件
                    self.refreshControl?.endRefreshing()
                    // 恢复上拉刷新标记
                    self.isPullup = false;
                    //刷新表格
                    if shouldRefresh {
                        self.tableview?.reloadData()
                    }
                })
            })
        }
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    func showFriend() {
        let vc = WBDemoViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
}
// MARK: - 表格数据方法
extension WBHomeViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 0. 取出视图模型，根据视图模型判断可重用 cell
        let vm = listViewModel.statusList[indexPath.row]
        
        let cellId = (vm.status.retweeted_status != nil) ? retweetedCellId : originalCellId
        
        // 1. 取 cell - 本身会调用代理方法(如果有)
        // 如果没有，找到 cell，按照自动布局的规则，从上向下计算，找到向下的约束，从而计算动态行高
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! WBStatusCell
        
        // 2. 设置 cell
        cell.viewModel = vm
        
        // --- 设置代理 ---
        // 如果用 block 需要在数据源方法中，给每一个 cell 设置 block
        // cell.completionBlock = { // ... }
        // 设置代理只是传递了一个指针地址
        cell.delegate = self as? WBStatusCellDelegate
        
        //3.返回cell
        return cell;
    }
}

// MARK: - WBStatusCellDelegate
extension WBHomeViewController: WBStatusCellDelegate {
    
    func statusCellDidSelectedURLString(cell: WBStatusCell, urlString: String) {
        
        let vc = WBWebViewController()

        vc.urlString = urlString

        navigationController?.pushViewController(vc, animated: true)
    }
}
extension WBHomeViewController {
    
    override func setUpTableView() {
        super.setUpTableView()
        //设置导航栏
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontSize: 16, target: self, action: #selector(showFriend), isBack: false)
        
        // 注册原型 cell
        tableview?.register(UINib(nibName: "WBStatusNormalCell", bundle: nil), forCellReuseIdentifier: originalCellId)
        tableview?.register(UINib(nibName: "WBStatusRetweetedCell", bundle: nil), forCellReuseIdentifier: retweetedCellId)

        // 设置行高
        tableview?.rowHeight = UITableViewAutomaticDimension
        tableview?.estimatedRowHeight = 300
        
        // 取消分割线
        tableview?.separatorStyle = .none
        
        // 设置导航栏标题
        setupNavTitle()
    }
    
    //设置导航栏标题
    private func setupNavTitle() {
        let title = WBNetworkManager.shared.userAccount.screen_name
        
        let button = WBTitleButton(title: title)
        
        navItem.titleView = button
        
        button.addTarget(self, action: #selector(onclickTitleButton(btn:)), for: .touchUpInside)
    }
    
    @objc func onclickTitleButton(btn: UIButton) {
        // 设置选中状态
        btn.isSelected = !btn.isSelected
    }
}

